package com.honey.mybatis.generator.mappper;

import java.util.List;

import com.honey.compilation.xml.XmlElement;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.Column;
import com.honey.core.dbmapping.structure.Schema;
import com.honey.core.dbmapping.structure.Table;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.core.utils.EmptyUtility;
import com.honey.mybatis.generator.MybatisPlugin;

public class VirtualDeleteByPrimaryKey extends AbstractMybatisMapper{

	public VirtualDeleteByPrimaryKey(MybatisPlugin belongPlugin) {
		super(belongPlugin);
	}

	public void appendElement(XmlElement parent, Schema schema, IntrospectSchemaColumn introspectSchemaColumn ){
		StringBuilder set = new StringBuilder();
		boolean bool =false ;
		for(Column column : introspectSchemaColumn.allColumns() ){
			String value = ((TableColumn)column).getVirtualDeleteValue();
			if( column instanceof TableColumn && value !=null){
				String key = column.getName();
				if( bool ){
					set.append(" , " );
				}else{
					bool = true ;
				}
				String c = column.isJdbcCharacterColumn()? "'": "";
				set.append( key)
				.append(" = ").append(c)
				.append(value).append(c);
			}
		}
		if( bool ){
			List<TableColumn> list = null;
			if( schema instanceof Table ){
				IntrospectTableColumn introspectTableColumn = (IntrospectTableColumn)introspectSchemaColumn;
				if( EmptyUtility.isListEmpty(introspectTableColumn.primaryKeyColumns()))
					return ;
				else
					list = introspectTableColumn.primaryKeyColumns();
			}
			
			parent.addNewLine();
			parent.addComments(
				"按照主键虚拟删除记录, 更新\""+set.toString()+"\"."
			);
			
			XmlElement delete = new XmlElement(parent,"update")
			.addAttribute("id",MapperConstant.VIRTUAL_DELETE_BY_PRIMARY_KEY_MAPPER_ID)
			.addAttribute("timeout", mybatisPlugin.getConnectionTimeOut())
			.addAttribute("flushCache", "true");
			if( list.size() ==1){
				delete.addAttribute("parameterType",list.get(0).getFullyQualifiedJavaType().getLongName());
			}else{
				delete.addAttribute("parameterType","map");
			}
			delete.addTextElement("UPDATE " + schema.getName() +" SET "+ set.toString());
			StringBuilder sb = new StringBuilder().append("WHERE ");
			boolean comma = false;
			for(TableColumn column : list ){
				if (comma)sb.append(" AND "); else comma = true;
				sb.append(column.getName()).append(" = #{")
				.append(column.getJavaProperty()).append(",jdbcType=").append(JdbcTypeName.getJdbcTypeName(column.getJdbcType()))
				.append("}");
			}
			delete.addTextElement(sb.toString());
		}
	}
}
